//
//  QqChannelApi.m
//  kq_flutter_core_widget
//
//  Created by wtb on 2024/12/29.
//

#import "QqChannelApi.h"
#import <TencentOpenAPI/QQApiInterface.h>
#import <TencentOpenAPI/TencentOAuth.h>

static QqChannelApi *qqApi = nil;

@interface QqChannelApi()<TencentSessionDelegate,QQApiInterfaceDelegate>

@property(nonatomic, copy) FlutterResult fResult;
@property(nonatomic, strong) TencentOAuth *oauth;
@property(nonatomic, strong) NSMutableArray *tencentPermissions;

@end


@implementation QqChannelApi

+(instancetype _Nullable)defualtQqChannelApi{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (qqApi == nil) {
            qqApi = [[QqChannelApi alloc] init];
            qqApi.oauth = [TencentOAuth sharedInstance];
            // 这个是说到时候你去qq那拿什么信息
            qqApi.tencentPermissions = [NSMutableArray arrayWithArray:@[/** 获取用户信息 */
                                                                   kOPEN_PERMISSION_GET_USER_INFO,
                                                                   /** 移动端获取用户信息 */
                                                                kOPEN_PERMISSION_GET_SIMPLE_USER_INFO,
                                                                   /** 获取登录用户自己的详细信息 */
                                                                kOPEN_PERMISSION_GET_INFO]];
            [TencentOAuth setIsUserAgreedAuthorization:YES];
        }
    });
    return qqApi;
}

+ (BOOL)handleOpenURL:(NSURL *)url
{
    return
        [QQApiInterface handleOpenURL:url
                             delegate:[QqChannelApi defualtQqChannelApi]] ||
        ([TencentOAuth CanHandleOpenURL:url] && [TencentOAuth HandleOpenURL:url]);
}

+ (BOOL)continueUserActivity:(NSUserActivity *)userActivity
{
    if ([userActivity.activityType
            isEqualToString:NSUserActivityTypeBrowsingWeb]) {
        NSURL *url = userActivity.webpageURL;
        if (url != nil) {
            return [QQApiInterface handleOpenUniversallink:url delegate:[QqChannelApi defualtQqChannelApi]] ||
                   ([TencentOAuth CanHandleUniversalLink:url] &&
                    [TencentOAuth HandleUniversalLink:url]);
        }
    }
    return NO;
}

//-(void)isInitialQqApp:(FlutterResult)result{
//    BOOL isInitial = [TencentOAuth iphoneQQInstalled];
//    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
//    [dic setValue:isInitial?@"1":@"0" forKey:@"code"];
//    result(dic);
//}

//-(void)registerQq:(FlutterMethodCall *)call result:(FlutterResult)result{
//    self.fResult = result;
//    NSString *appId = call.arguments[@"appId"];
//    NSString *universalLink = call.arguments[@"universalLink"];
//    if (universalLink != nil) {
//        [self.oauth setupAppId:appId enableUniveralLink:true universalLink:universalLink delegate:self];
//    } else {
//        [self.oauth setupAppId:appId enableUniveralLink:NO universalLink:nil delegate:self];
//    }
//}

#pragma mark - 授权QQ

-(void)handleQqAuthCall:(FlutterMethodCall *)call result:(FlutterResult)result{
    if (![TencentOAuth iphoneQQInstalled]) {
        //没有安装
        result(@{@"code":@"2"});
        return;
    }
    if (call.arguments[@"appId"]) {
         //存在appid
        NSString *appId = call.arguments[@"appId"];
        NSString *universalLink = call.arguments[@"universalLink"];
        //universalLink 有值无值 需要特殊对待
        if (universalLink != nil) {
            [self.oauth setupAppId:appId enableUniveralLink:true universalLink:universalLink delegate:self];
        } else {
            [self.oauth setupAppId:appId enableUniveralLink:NO universalLink:nil delegate:self];
        }
    }
    if (self.oauth != nil) {
        self.fResult = result;
//        NSNumber *qrcode = call.arguments[@"appId"];
        self.oauth.authMode = kAuthModeClientSideToken;
        [self.oauth authorize:self.tencentPermissions];
    }
}

-(void)handleQqShareTextCall:(FlutterMethodCall *)call result:(FlutterResult)result{
    if (![TencentOAuth iphoneQQInstalled]) {
        //没有安装
        result(@(-3));
        return;
    }
    if (call.arguments[@"appId"]) {
         //存在appid
        NSString *appId = call.arguments[@"appId"];
        NSString *universalLink = call.arguments[@"universalLink"];
        //universalLink 有值无值 需要特殊对待
        if (universalLink != nil) {
            [self.oauth setupAppId:appId enableUniveralLink:true universalLink:universalLink delegate:self];
        } else {
            [self.oauth setupAppId:appId enableUniveralLink:NO universalLink:nil delegate:self];
        }
    }
    self.fResult = result;
    NSString *summary = call.arguments[@"content"];
    QQApiTextObject *object = [QQApiTextObject objectWithText:summary];
    SendMessageToQQReq *req = [SendMessageToQQReq reqWithContent:object];
    [QQApiInterface sendReq:req];
}

-(void)handleQqShareWebCall:(FlutterMethodCall *)call result:(FlutterResult)result{
    if (![TencentOAuth iphoneQQInstalled]) {
        //没有安装
        result(@(-3));
        return;
    }
    if (call.arguments[@"appId"]) {
        //存在appid
        NSString *appId = call.arguments[@"appId"];
        NSString *universalLink = call.arguments[@"universalLink"];
        //没有
        //universalLink 有值无值 需要特殊对待
        if (universalLink != nil) {
            [self.oauth setupAppId:appId enableUniveralLink:true universalLink:universalLink delegate:self];
        } else {
            [self.oauth setupAppId:appId enableUniveralLink:NO universalLink:nil delegate:self];
        }
    }
    self.fResult = result;
    NSString *title = call.arguments[@"title"];
    NSString *summary = call.arguments[@"desc"];
    NSString *imageUri = call.arguments[@"iconUrl"];
    NSString *targetUrl = call.arguments[@"url"];

    QQApiNewsObject *object = nil;
    NSURL *imageUrl = [NSURL URLWithString:imageUri];
    if ([@"file" isEqualToString:imageUrl.scheme]) {
        NSData *imageData = [NSData dataWithContentsOfFile:imageUrl.path];
        object = [QQApiNewsObject objectWithURL:[NSURL URLWithString:targetUrl]
                                          title:title
                                    description:summary
                               previewImageData:imageData];
    } else {
        object = [QQApiNewsObject objectWithURL:[NSURL URLWithString:targetUrl]
                                          title:title
                                    description:summary
                                previewImageURL:imageUrl];
    }
    SendMessageToQQReq *req = [SendMessageToQQReq reqWithContent:object];
    [QQApiInterface sendReq:req];
}

-(void)handleQqShareImageCall:(FlutterMethodCall *)call result:(FlutterResult)result{
    if (![TencentOAuth iphoneQQInstalled]) {
        //没有安装
        result(@(-3));
        return;
    }
    if (call.arguments[@"appId"]) {
        //存在appid
        NSString *appId = call.arguments[@"appId"];
        NSString *universalLink = call.arguments[@"universalLink"];
        //没有
        //universalLink 有值无值 需要特殊对待
        if (universalLink != nil) {
            [self.oauth setupAppId:appId enableUniveralLink:true universalLink:universalLink delegate:self];
        } else {
            [self.oauth setupAppId:appId enableUniveralLink:NO universalLink:nil delegate:self];
        }
    }
    self.fResult = result;
    NSString *imageUri = call.arguments[@"localPath"];
    NSURL *imageUrl = [NSURL URLWithString:imageUri];
    NSData *imageData = [NSData dataWithContentsOfFile:imageUrl.path];
    QQApiImageObject *object = [QQApiImageObject objectWithData:imageData
                                               previewImageData:nil
                                                          title:nil
                                                    description:nil];
    SendMessageToQQReq *req = [SendMessageToQQReq reqWithContent:object];
    [QQApiInterface sendReq:req];
}

#pragma mark - TencentSessionDelegate

///登录成功后的回调
- (void)tencentDidLogin
{
    if (self.fResult != nil) {
        NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
        if (_oauth.accessToken != nil && _oauth.accessToken.length > 0) {
            NSString *openId = _oauth.openId;
            NSString *accessToken = _oauth.accessToken;
            if (_oauth.authMode == kAuthModeServerSideCode) {
                // 将 code 的值赋给 accessToken, 避免字段功能混淆
                // 同时官方文档也有说明通过此接口获取的 code 实际上就是 accessToken
                accessToken = [_oauth getServerSideCode];
            }
            long long expiresIn =
                ceil(_oauth.expirationDate.timeIntervalSinceNow); // 向上取整
            long long createAt = [[NSDate date] timeIntervalSince1970] * 1000.0;
            [dictionary setValue:@"0" forKey:@"code"];
            [dictionary setValue:openId forKey:@"openId"];
            [dictionary setValue:accessToken forKey:@"accessToken"];
            [dictionary setValue:[NSNumber numberWithLongLong:expiresIn]
                          forKey:@"expires_in"];
            [dictionary setValue:[NSNumber numberWithLongLong:createAt]
                          forKey:@"create_at"];
        } else {
            // 登录失败
            [dictionary setValue:@"1" forKey:@"code"];
        }
        self.fResult(dictionary);
    }
}

#pragma mark - 登录失败后的回调  cancelled 代表用户是否主动退出登录

- (void)tencentDidNotLogin:(BOOL)cancelled
{
    if (self.fResult != nil) {
        NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
        if (cancelled) {
            // 取消登录
            [dictionary setValue:@"-1" forKey:@"code"];
            [dictionary setValue:@"取消登录" forKey:@"msg"];
        } else {
            // 登录失败
            [dictionary setValue:@"1" forKey:@"code"];
            [dictionary setValue:@"登录失败" forKey:@"msg"];
        }
        self.fResult(dictionary);
    }
}

#pragma mark - 登录时网络有问题的回调

- (void)tencentDidNotNetWork 
{
    // 登录失败
    if (self.fResult != nil) {
        NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
        [dictionary setValue:@"1" forKey:@"code"];
        [dictionary setValue:@"登录失败" forKey:@"msg"];
        self.fResult(dictionary);
    }
}

#pragma mark - QQApiInterfaceDelegate

- (void)onResp:(QQBaseResp *)resp
{
    if (self.fResult != nil) {
        if ([resp isKindOfClass:[SendMessageToQQResp class]]) {
            switch (resp.result.intValue) {
                case 0:
                    // 分享成功
                    self.fResult(@0);
                    break;
                case -4:
                    // 用户取消
                    self.fResult(@3);
                    break;
                default:
                    self.fResult(@1);
                    break;
            }
        }
    }
}

- (void)isOnlineResponse:(NSDictionary *)response
{
    
}


- (void)onReq:(QQBaseReq *)req 
{
    
}


@end
